Reverse Integer

Time: O(LogN)=O(1); Space: O(1); easy

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: num = 123

Output: 321

Example 2:

Input: num = -123

Output: -321

Example 3:

Input: num = 120

Output: 21

Note:

  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: (-2^31, 2^31-1). For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Follow up:

  1. If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

  2. Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

  3. Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

[1]:
class Solution1(object):
    def reverse(self, num) -> int:
        """
        :type num: int
        :rtype: int
        """
        if num < 0:
            return -self.reverse(-num)

        result = 0
        while num:
            result = result * 10 + num % 10
            num //= 10
        return result if result <= 0x7fffffff else 0  # Handle overflow
[5]:
s = Solution1()
num = 123
assert s.reverse(num) == 321
num = -123
assert s.reverse(num) == -321
num = 120
assert s.reverse(num) == 21
[3]:
class Solution2(object):
    def reverse(self, num) -> int:
        """
        :type num: int
        :rtype: int
        """
        if num < 0:
            num = int(str(num)[::-1][-1] + str(num)[::-1][:-1])
        else:
            num = int(str(num)[::-1])
        num = 0 if abs(num) > 0x7FFFFFFF else num
        return num
[6]:
s = Solution2()
num = 123
assert s.reverse(num) == 321
num = -123
assert s.reverse(num) == -321
num = 120
assert s.reverse(num) == 21
[7]:
class Solution3(object):
    def cmp(self, a, b):
        return (a > b) - (a < b)

    def reverse(self, num) -> int:
        """
        :type num: int
        :rtype: int
        """
        s = self.cmp(num, 0)
        r = int(str(s * num)[::-1])
        return s * r * (r < 2 ** 31)
[8]:
s = Solution3()
num = 123
assert s.reverse(num) == 321
num = -123
assert s.reverse(num) == -321
num = 120
assert s.reverse(num) == 21